'''
    Pegaso
    Copyright (c) 2012 Dario Tognacci

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
'''

import modgrammar
from structures import *
from grammar import *
from util import *
from wrapper import *
import re
import modgrammar


def load_statements_table(input_file):
    
    # Print the grammar in BNF
    try:
        bnf = open("bnf.txt", "w")
        bnf.writelines(modgrammar.generate_ebnf(CGrammarDec))
        bnf.close()
    except IOError as e:
        manage_error(e,"Error during creation of BNF file.")
    
    parser = CGrammarDec.parser()
    header = ""

    # I need to do some stuff before processing the grammar!
    for line in input_file:
        # Look for a line splitted in two
        if line[-2:] == "\\\n":
            line = line[:-2]
            util.removed_lines = util.removed_lines + 1
        line = remove_multiline_comment(line)
        # Look for singleline comment
        if line.find("//") is not -1:
            line = (re.split("//", line))[0] + "\n"
        header = header + line
    
    # If enabled, this statement print the header file after comment removing.
    #print(header)
    
    # I need to look for a directive for the preprocessor which substitutes the
    # * pointer symbol with a string. If present, I have to preprocess this
    # directive before continue. It is in the form:
    #   #define SOME_STRING *
    preproc_ptr = re.compile("\#define (?P<id>.*) \*")
    match = re.search(preproc_ptr, header)
    if match is not None:
        # It takes the substitutive name
        preproc_ptr_name = match.group('id')
        occurences = re.compile(preproc_ptr_name)
        # Remove the directive
        header = preproc_ptr.sub('', header)
        util.removed_lines = util.removed_lines + 1
        # Substituite alle the occurences of the substitutive name with *
        header = occurences.sub('*', header)
        
    try:
        parser.parse_string(header + "\n", multi=True)
    except ParseError as e:
        manage_error(e)
